package com.rst.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.rst.model.Classe;
import com.rst.model.Section;
import com.rst.service.ClassService;
import com.rst.service.SectionService;


@Controller
public class SectionController {
	@Autowired
	SectionService sectionService;
	
	@Autowired
	ClassService classService;

	@RequestMapping(value="/addSection", method=RequestMethod.GET)
	public ModelAndView addSection()
	{
		ModelAndView mav = new ModelAndView("section/createSection");
		Section section = new Section();
		List<Classe> classList = classService.getClassList();
		mav.addObject("classList", classList);
		mav.getModelMap().put("sections", section);
		return mav;
	}
	
	@RequestMapping(value="/saveSection", method=RequestMethod.POST)
	public String saveSection(@ModelAttribute("section")Section section, BindingResult result, SessionStatus status)
	{
		Long id = sectionService.save(section);
		status.setComplete();
		return "redirect:managesection.htm";
	}
	
	@RequestMapping(value="/editSection", method=RequestMethod.GET)
	public ModelAndView editSection(@RequestParam("id")Long sectionId)
	{
		ModelAndView mav = new ModelAndView("section/editSection");
		Section section = sectionService.getSectionById(sectionId);
		List<Classe> classList = classService.getClassList();
		mav.addObject("classList", classList);
		mav.addObject("editSection", section);
		return mav;
	}
	
	@RequestMapping(value="/updateSection", method=RequestMethod.POST)
	public String updateSection(@ModelAttribute("updateSection") Section section, SessionStatus status,
			@RequestParam("id")Long sectionId)
	{
		
		sectionService.update(section,sectionId);	
		status.setComplete();
		return "redirect:managesection.htm";
	}

	@RequestMapping(value="/managesection", method=RequestMethod.GET)
	public ModelAndView manageClass()
	{
		ModelAndView mav = new ModelAndView("section/manageSection");
		List<Section> sectionList = sectionService.getSectionList();;
		mav.addObject("sectionList", sectionList);
		return mav;
	}
	@RequestMapping(value="/deleteSection", method=RequestMethod.GET)
	public String deleteSection(@RequestParam("id")Long sectionId , HttpServletRequest request)
	{
		String status = sectionService.deleteSection(sectionId);
		return "redirect:managesection.htm" ;
	}
	
}
